package game.view.scene
{
	import as3isolib.display.IsoSprite;
	import as3isolib.display.IsoView;
	import as3isolib.display.scene.IsoGrid;
	import as3isolib.display.scene.IsoScene;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.LocalConnection;
	import flash.system.System;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import game.common.CustomBitmap;
	import game.common.Reflection;
	import game.controller.GameDispatcher;
	import game.event.EventName;
	import game.event.GameEvent;
	import game.managers.StageProxy;
	import game.managers.StateManager;
	import game.model.SceneModel;

	public class Scene extends Sprite
	{
		private var elementLayer:Sprite;
		private var _mainBG:CustomBitmap;
		private var elementList:Dictionary;
		/**as3isolib地图引擎*/
		private var floorScene:IsoScene;
		private var wallScene:IsoScene;
		private var itemScene:IsoScene;

		private var grid:IsoGrid;
		private var view:IsoView;

		private var _model:SceneModel=SceneModel.getInstance();

		private var _cook:Cooker;
		private var _employee:Employee;

		/**固定顾客坐标*/
		private var _customEndPt1:Point=new Point(3, 2);
		private var _customEndPt2:Point=new Point(3, 4)
		private var _customStartPt:Point=new Point(0, 1);
		/**固定默认服务员坐标*/
		private var _emEndPt1:Point=new Point(1, 2);
		private var _emEndPt2:Point=new Point(2, 5);
		private var _emStartPt:Point=new Point(2, 6);

		public var aliveCusArr:Array=[];

		private var m:int;

		public function Scene()
		{
			init();
		}

		private function init():void
		{
			elementList=new Dictionary();

			_model.addEventListener(EventName.INIT_SCENE, buildScene);

			addEventListener(Event.ENTER_FRAME, enterFrame);


		}

		/**每次缓动均更新视图*/
		private function enterFrame(e:Event):void
		{
			itemScene.render();
		}


		/**
		 * 建立场景
		 * */
		private function buildScene(e:Event):void
		{
			_mainBG=new CustomBitmap();
			_mainBG.source="mainBG";
			_mainBG.x=-800;
			_mainBG.y=-720;
			addChildAt(_mainBG, 0);

			floorScene=new IsoScene();
			wallScene=new IsoScene();
			itemScene=new IsoScene();



			grid=new IsoGrid();
			grid.x=-80;
			grid.y=-110;
			grid.cellSize=_model.gridSize;
			grid.showOrigin=false;
			grid.setGridSize(_model.width, _model.length, _model.height);


			//添加地板
			for (var i:int=0; i < _model.xml.floor.resource.length(); i++)
			{
				var floorSprite:IsoSprite=new IsoSprite();
				floorSprite.sprites=[Reflection.getClass(_model.xml.floor.resource[i].name)];
				floorSprite.moveTo(_model.xml.floor.resource[i].x, _model.xml.floor.resource[i].y, 0);
				floorScene.addChild(floorSprite);
			}
			floorScene.addChild(grid);

			//添加墙
			for (var j:int=0; j < _model.xml.wall.resource.length(); j++)
			{
				var wallSprite:IsoSprite=new IsoSprite();
				wallSprite.sprites=[Reflection.getClass(_model.xml.wall.resource[j].name)];
				wallSprite.moveTo(_model.xml.wall.resource[j].x, _model.xml.wall.resource[j].y, 0);
				wallScene.addChild(wallSprite);
			}


			for (var i2:int=0; i2 < _model.xml.item.resource.length(); i2++)
			{
				var itemSprite:IsoSprite=new IsoSprite();
				itemSprite.sprites=[Reflection.createMovieClip(_model.xml.item.resource[i2].name)];
				itemSprite.moveTo(_model.xml.item.resource[i2].x, _model.xml.item.resource[i2].y, 0);
				trace((itemSprite.sprites[0] as MovieClip).width + " " + (itemSprite.sprites[0] as MovieClip).height);
				itemSprite.setSize((itemSprite.sprites[0] as MovieClip).x,(itemSprite.sprites[0] as MovieClip).y,0);
				elementList[String(_model.xml.item.resource[i2].name)]=itemSprite;
				if (String(_model.xml.item.resource[i2].name).search("customer") != -1 || String(_model.xml.item.resource[i2].name).search("guo") != -1 || String(_model.xml.item.resource[i2].name).search("dish") != -1 || String(_model.xml.item.resource[i2].name).search("tips") != -1)
				{
					itemSprite.sprites[0].visible = false;
					//continue;
				}

				itemScene.addChild(itemSprite);

			}


			view=new IsoView();
			view.setSize(StageProxy.stageWidth(), StageProxy.stageHeight());
			view.addScene(floorScene);
			view.addScene(wallScene);
			view.addScene(itemScene);

			view.render(true);
			addChild(view);

			/**厨师初始化*/
			_cook=new Cooker(onCookFinish);
			_cook.chefSp=elementList["cook2"];

			/**默认服务员初始化*/
			_employee=new Employee();
			_employee.emSp=elementList["employee"];

			addCustomer(_customStartPt, _customEndPt1);
		}


		private var str:String="customer";
		/**顾客模型编号,总共2个*/
		private var _cusNum:int=1;
		/**当前顾客总数,最大为2*/
		private var _cusCount:int=1;
		private var _isWaiting:Boolean=false;
		private var _nowDish:IsoSprite;
		private var _nowDishMC:MovieClip;


		/**
		 * 添加顾客
		 * */
		private function addCustomer(startPt:Point, endPt:Point):void
		{
			var cus:Customer=new Customer();
			cus.cusSp=elementList[String(str + _cusCount)];
			elementList[String(str + _cusCount)].sprites[0].visible = true;
			cus.tips=elementList["tips"];
			cus.move(startPt, endPt);
			_model.pathGrid.setWalkable(endPt.x, endPt.y, false);
			aliveCusArr.push(cus);
			//itemScene.addChild(cus.cusSp);
			
			if (aliveCusArr.length >= 2)
			{
				isWaiting=true;
			}
		}


		/**
		 * 检测alivearr里面是否有2个人,若有2个人同时坐着不动的话则返回true
		 * */
		private function checkCusSitState(item:Customer, index:int, arr:Array):Boolean
		{
			if (item.nowState == Customer.CUSTOMER_SIT && arr.length >= 2)
			{
				return true;
			}
			else
				return false;

		}

		/**
		 * isWaiting表示是否需要等待,若需要等待的话则到上一名顾客离开房间后再开始煮菜
		 * */
		public function onCookingStart():void
		{
			_tempCus=aliveCusArr[0] as Customer;

			/**当返回true的时候将isWaiting变为false,让循环能继续下去*/
			if (aliveCusArr.every(checkCusSitState))
			{
				isWaiting=false;
			}


			if (isWaiting == false)
			{
				_cook.isCooking(true);
				//将厨师的锅添加到场景
				//itemScene.addChild(elementList["guo"] as IsoSprite);
				(elementList["guo"] as IsoSprite).sprites[0].visible = true;
				//根据顾客人数决定当前的碟子应该是哪张台
				switch (_cusCount)
				{
					case 1:
						_nowDish=elementList["dish1"] as IsoSprite;
						break;
					case 2:
						_nowDish=elementList["dish2"] as IsoSprite;
						break;
				}
			}
			else
			{
				_cook.isCooking(false);
			}
		}


		/**
		 * 当厨师煮完之后的回调函数
		 * */
		private function onCookFinish():void
		{
			/**移除厨师的锅*/
//			if (itemScene.contains(elementList["guo"] as IsoSprite))
//			{
//				itemScene.removeChild(elementList["guo"] as IsoSprite);
//			}
			(elementList["guo"] as IsoSprite).sprites[0].visible = false;
			_employee.nowState=Employee.EMPLOYEE_SERV;

			switch (_cusCount)
			{
				case 1:
					_employee.move(_emStartPt, _emEndPt1);
					break;
				case 2:
					_employee.move(_emStartPt, _emEndPt2);
					break;
			}

			/**食物数量改变*/
			GameDispatcher.getInstance().dispatchEvent(new GameEvent(EventName.FOOD_CHANGE));

		}


		/**用于保存房间现有顾客数组的引用*/
		private var _tempCus:Customer;


		/**
		 * 在上一名顾客吃东西时将添加一名新顾客进入房间
		 * */
		public function onCustomerEating():void
		{

			if (aliveCusArr.every(checkCusSitState))
			{
				/**当出现bug,循环修复时则从端盘给第一个进来的,盘子位置也需要换一下*/
				switch (_cusCount)
				{
					case 1:
						_nowDish=elementList["dish2"] as IsoSprite;
						break;
					case 2:
						_nowDish=elementList["dish1"] as IsoSprite;
						break;
				}
			}
			else
			{


				addRole();
			}

			_tempCus.changeState(_tempCus.cusSp, StateManager.customerEatLeft);
			_tempCus.nowState=Customer.CUSTOMER_EAT;
			//itemScene.addChild(_nowDish);
			_nowDish.sprites[0].visible = true;

		}


		/**根据当前场景顾客决定新顾客的位置*/
		public function addRole():void
		{
			_cusCount++;
			if (_cusCount > 2)
			{
				_cusCount=1;
			}
			switch (_cusCount)
			{
				case 1:
					addCustomer(_customStartPt, _customEndPt1);
					break;
				case 2:
					addCustomer(_customStartPt, _customEndPt2);
					break;
			}
		}


		/**
		 * 顾客吃完东西之后的处理函数
		 * */
		public function onCustomerEatFinish():void
		{
			_tempCus.changeState(_tempCus.cusSp, StateManager.customerSitLeft);

			/**获得当前盘子的mc,并将其设置到吃完的状态*/
			_nowDishMC=_nowDish.sprites[0] as MovieClip;
			_nowDishMC.gotoAndStop(3);

			/**将tips添加进场景,并且将其初始位置设好*/
			//itemScene.addChild(_tempCus.tips as IsoSprite);
			(elementList["tips"] as IsoSprite).sprites[0].visible = true;
			_tempCus.setTipsPosition();
		}


		/**
		 * 付款结束的处理函数
		 * */
		public function onPayingFinish():void
		{
//			if (itemScene.contains(_nowDish))
//				itemScene.removeChild(_nowDish);
			_nowDish.sprites[0].visible = false;
			_nowDishMC.gotoAndStop(1);

			switch (_cusNum)
			{
				case 1:
					_model.pathGrid.setWalkable(_customEndPt1.x, _customEndPt1.y, true);
					_tempCus.move(_customEndPt1, _customStartPt);
					break;
				case 2:
					_model.pathGrid.setWalkable(_customEndPt2.x, _customEndPt2.y, true);
					_tempCus.move(_customEndPt2, _customStartPt);
					break;
			}

			_tempCus.nowState=Customer.CUSTOMER_LEAVE;
			/**将回调函数传进customer等顾客人物离开房间之后执行*/
			_tempCus.leaveFun=removeCustomer;
			/**将tipsMC设置成 "好评" 的状态*/
			_tempCus.setGoodTips();

			/**金钱改变*/
			GameDispatcher.getInstance().dispatchEvent(new GameEvent(EventName.MONEY_CHANGE));

		}

		private var _ti:Timer;

		/**
		 * 移除顾客
		 * */
		private function removeCustomer():void
		{

			/**将_tipsMC重新设成付款状态,因为用的都是同一个引用,
			 * 所以在上一名离开房间之后把tipsMC重新设成付款状态
			 * 方便下一名顾客初始化不用调状态*/
			//_tipsMC.gotoAndStop(StateManager.cusPayTips);
			_tempCus=aliveCusArr.shift();
			
//			if(_tempCus && _tempCus.tips && itemScene.contains(_tempCus.tips))
//				itemScene.removeChild(_tempCus.tips);
			(elementList["tips"] as IsoSprite).sprites[0].visible = false;
			isWaiting=false;
			_cusNum++;
			if (_cusNum > 2)
			{
				_cusNum=1;
			}

			/**如果3个格子都为空或餐厅一个顾客都没有*/
			if (Global.foodDataArr.every(foodDataArrIsNull) || aliveCusArr.length == 0)
			{
				addRole();
			}
			/**
			 * 这里判断是否已经是离开状态了,如果是则不煮,等下一个顾客进来坐下才开始煮菜
			 * */
			else if (aliveCusArr[0].nowState != Customer.CUSTOMER_LEAVE && Global.foodDataArr.every(foodDataArrIsNull) == false)
			{
				/**等上一名顾客离开房间之后再开始煮菜,将isWaiting设置成false,因为屏幕中
				 * 只剩下一名顾客
				 * */
				onCookingStart();
			}
			else if (Global.foodDataArr.every(foodDataArrIsNull) == false && aliveCusArr.length == 1 && aliveCusArr[0].nowState == Customer.CUSTOMER_SIT)
			{
				onCookingStart();

			}
			else
			{
				trace(123);
			}

		}


		private function foodDataArrIsNull(item:*, index:int, arr:Array):Boolean
		{
			if (item == null)
			{
				return true;
			}
			else
			{
				return false;
			}

		}

		/**数组的第几个元素*/
		private var _moveNum:int;

		public function onNoFoodLeaving():void
		{
			if (aliveCusArr[0].onLeaveWalking == true)
			{
				_moveNum=1;
			}
			else if (aliveCusArr[0].nowState == Customer.CUSTOMER_LEAVE)
			{
				_moveNum=0;
			}
			//itemScene.addChild(elementList["tips"] as IsoSprite);
			(elementList["tips"] as IsoSprite).sprites[0].visible = true;
			aliveCusArr[_moveNum].setTipsPosition();


			switch (_cusNum)
			{
				case 1:
					_model.pathGrid.setWalkable(_customEndPt1.x, _customEndPt1.y, true);
					aliveCusArr[_moveNum].move(_customEndPt1, _customStartPt);
					break;
				case 2:
					if (_moveNum == 1)
					{
						_model.pathGrid.setWalkable(_customEndPt1.x, _customEndPt1.y, true);
						aliveCusArr[_moveNum].move(_customEndPt1, _customStartPt);
						break;
					}
					_model.pathGrid.setWalkable(_customEndPt2.x, _customEndPt2.y, true);
					aliveCusArr[_moveNum].move(_customEndPt2, _customStartPt);
					break;
			}


			aliveCusArr[_moveNum].nowState=Customer.CUSTOMER_LEAVE;
			/**将回调函数传进customer等顾客人物离开房间之后执行*/
			aliveCusArr[_moveNum].leaveFun=removeCustomer;
			/**将tipsMC设置成 "好评" 的状态*/
			aliveCusArr[_moveNum].setTimeTips();
		}


		public function dispose():void
		{
			if (contains(view))
			{
				removeChild(view);
				view=null;
			}
			floorScene.removeAllChildren();
			floorScene=null;

			wallScene.removeAllChildren();
			wallScene=null;

			itemScene.removeAllChildren();
			itemScene=null;


			_tempCus=null;
			_nowDish=null;
			_nowDishMC=null;
		}

		/**当前进入的顾客是否需要等待*/
		public function get isWaiting():Boolean
		{
			return _isWaiting;
		}

		/**
		 * @private
		 */
		public function set isWaiting(value:Boolean):void
		{
			_isWaiting=value;
		}


	}
}